<script setup lang="ts">
import { ref, markRaw } from "vue";
import { useColumns } from "./columns";
import Plus from "~icons/ep/plus";
import Delete from "~icons/ep/delete";
import UploadIcon from "~icons/ri/upload-2-line?width=26&height=26";
import "plus-pro-components/es/components/dialog-form/style/css";
import { getMenuList } from "@/api/system";
import { handleTree } from "@/utils/tree";
import { getKeyList } from "@pureadmin/utils";
import { addRole, setRole } from "@/api/system";
defineOptions({
  name: "SystemRole"
});
import {
  type PlusColumn,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import {
  type Action,
  genFileId,
  UploadInstance,
  UploadProps,
  ElMessageBox,
  ElMessage,
  UploadRawFile
} from "element-plus";
import { underscoreToCamel } from "@/utils/common";
const iconimageName = ref();
const previewImageUrl = ref();
const previewImageName = ref();
const showPreviewImage = ref(false);
const edit = ref(false);
const productImageRef = ref<UploadInstance>();

const treeRef = ref();
const treeData = ref([]);
const defaultCheckedKeys = ref([]);
const treeProps = {
  value: "id",
  label: "name",
  children: "children"
};
const powerMap = ref({});
const homeId = ref(0);
const getMenuOptions = async () => {
  try {
    const { data } = await getMenuList();

    const treeDD = handleTree(data, "id", "p_id");
    let vId = 90000;
    powerMap.value = {};
    treeDD.map(item => {
      if (item.name === "首页") {
        homeId.value = item.id;
        item.disabled = true;
        console.log("首页", homeId.value);
        return item;
      } else if (item.name === "系统设置") {
        item.disabled = true;
        item.children.forEach(element => {
          element.disabled = true;
        });
        return item;
      }

      if (item.children) {
        item.children.map(p => {
          if (p.power) {
            p.power.map(power => {
              power.id = vId;
              power.p_id = p.id;
              power.name = power.title;
              delete power.title;
              powerMap.value[vId] = power;
              // 这个用于编辑用  通过menuId和power.code 定位当前的vId，
              powerMap.value[`${p.id}_${power.code}`] = vId;
              vId++;
              return power;
            });
            p.children = p.power;
            p.power = undefined;
          }
          return p;
        });
      }
      return item;
    });
    treeData.value = treeDD;
  } catch (error) {
    console.error(error);
  }
};

const rules = {
  roleName: [
    {
      required: true,
      message: "角色名称必填"
    }
  ],
  roleType: [
    {
      required: true,
      message: "类型必填"
    }
  ],
  weight: [
    {
      required: true,
      message: "权重必填"
    }
  ]
};

const formColumns: PlusColumn[] = [
  {
    label: "角色名称",
    prop: "roleName",
    valueType: "input",
    tooltip: "请输入角色名称"
  },
  {
    label: "类型",
    prop: "roleType",
    valueType: "select",
    options: [
      {
        label: "平台",
        value: 1
      }
    ]
  },
  {
    label: "关联菜单",
    prop: "menus",
    tooltip: "权限菜单"
  },
  {
    label: "排序权重",
    prop: "weight",
    valueType: "input-number"
  }
];
const visible = ref(false);
const values = ref<FieldValues>({});
const props = defineProps({
  type: {
    type: Number,
    default: 1
  }
});
const { loading, columns, dataList, loadingConfig, adaptiveConfig, loadData } =
  useColumns(props.type);
function deleteClick(row) {
  ElMessage.info("暂未开发该功能");
  return;
  ElMessageBox.confirm("是否删除", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    draggable: true,
    type: "error",
    icon: markRaw(Delete),
    callback: async (action: Action) => {
      // 在这里执行删除操作
      if (action === "confirm") {
        console.log("执行删除操作");
        try {
          const params = {
            type: props.type,
            orderId: row.orderId,
            isDelete: 1
          };
          // const res = await setProductOrder(params);
          loadData();
          ElMessage.success("删除成功");
        } catch (error) {
          console.log(error, "error");
        }
      }
    }
  });
}
const editClick = async row => {
  // 获取所有菜单
  await getMenuOptions();
  const data = underscoreToCamel(row);
  Object.assign(values.value, data);
  const vIds = [homeId.value];
  data.menus.forEach(menu => {
    const menuId = menu.id;
    if (!vIds.includes(menuId)) {
      vIds.push(menuId);
    }
    menu.powerKey.forEach(power => {
      const findVId = powerMap.value[`${menuId}_${power}`];
      if (findVId) {
        vIds.push(findVId);
      }
    });
  });

  edit.value = true;
  visible.value = true;
  if (treeRef.value) {
    treeRef.value.setCheckedKeys(vIds);
  } else {
    defaultCheckedKeys.value = vIds;
  }
};

const add = async () => {
  await getMenuOptions();
  edit.value = false;
  values.value = { weight: 1, roleType: 1, menus: [] };
  visible.value = true;
  if (treeRef.value) {
    treeRef.value.setCheckedKeys([homeId.value]);
    console.log("d2");
  } else {
    console.log("d1");
    defaultCheckedKeys.value = [homeId.value];
  }
};
const confirmLoading = ref(false);
const handleSubmit = async (value: FieldValues) => {
  const updatedValues = { ...values.value };
  // const vIdss = treeRef.value.getCheckedKeys() as number[];
  // console.log("values.", updatedValues, vIdss);
  // return;
  // confirmLoading.value = true;
  const vIds = treeRef.value.getCheckedKeys() as number[];
  const resultMap = {};
  for (let i = 0; i < vIds.length; i++) {
    const vId = vIds[i];
    if (vId >= 9000) {
      const power = powerMap.value[vId];
      const code = power.code;
      const menusId = power.p_id;
      if (!resultMap[menusId]) {
        resultMap[menusId] = [];
      }
      resultMap[menusId].push(code);
    } else {
      // 这里的vId就是menusId
      if (!resultMap[vId]) {
        resultMap[vId] = [];
      }
    }
  }
  const menus = [];
  Object.entries(resultMap).forEach(([menusId, power]) => {
    menus.push({ menusId, power });
  });
  if (edit.value) {
    try {
      const params = {
        roleId: updatedValues.id,
        roleName: updatedValues.roleName,
        roleType: updatedValues.roleType,
        weight: updatedValues.weight,
        menus
      };
      // console.log("params", params);
      // return;
      await setRole(params);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
      ElMessage.success("修改成功");
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  } else {
    try {
      const params = {
        roleName: updatedValues.roleName,
        roleType: updatedValues.roleType,
        weight: updatedValues.weight,
        menus
      };
      await addRole(params);
      visible.value = false;
      confirmLoading.value = false;
      formRef.value?.formInstance?.resetFields();
      loadData();
    } catch (error) {
      confirmLoading.value = false;
      console.log(error, "error");
    }
  }
};
const handleIconImageSuccess: UploadProps["onSuccess"] = (res, file) => {
  console.log(
    "%cres===>>>",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    res,
    file
  );
  values.value.iconimage = res.data;
  iconimageName.value = file.name;
};
const handleIconImageRemove: UploadProps["onRemove"] = (file, files) => {
  console.log(
    "%cfile===>>>",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    file,
    files
  );
  values.value.iconimage = undefined;
  iconimageName.value = undefined;
};
/// 超出limit限制 先清空文件列表再执行上传
const handleIconImageExceed: UploadProps["onExceed"] = files => {
  console.log(
    "%cfiles===>>>",
    "color: MidnightBlue; background: Aquamarine; font-size: 20px;",
    files
  );
  productImageRef.value?.clearFiles();
  const file = files[0] as UploadRawFile;
  file.uid = genFileId();
  productImageRef.value?.handleStart(file);
  productImageRef.value?.submit();
};
const handlePreviewImage: UploadProps["onPreview"] = file => {
  previewImageName.value = file.name;
  previewImageUrl.value = file.url;
  showPreviewImage.value = true;
};

const treeChecked = (data, all) => {
  const cNode = treeRef.value.getNode(data.id); // 当前节点
  checkParent(cNode);

  // pNode.indeterminate = true;

  // treeRef.value.setCheckedKeys(all.checkedKeys, false);
};

const checkParent = node => {
  const parent = node.parent;
  if (!parent) {
    return;
  }
  if (node.checked) {
    parent.checked = true;
    parent.indeterminate = !parent.childNodes.every(child => child.checked);
  } else {
    parent.checked = parent.childNodes.some(child => child.checked);
    parent.indeterminate = parent.childNodes.some(child => child.checked);
  }
  checkParent(parent);
};

const formRef = ref();
</script>

<template>
  <ElCard>
    <template #header>
      <ElPageHeader :icon="null">
        <template #title>
          <h3>角色管理</h3>
        </template>
        <template #extra>
          <div class="flex flex-row items-end justify-end">
            <el-button type="primary" @click="add">
              <el-icon :size="15" color="#fff">
                <IconifyIconOffline :icon="Plus" />
              </el-icon>
              添加角色
            </el-button>
          </div>
        </template>
      </ElPageHeader>
    </template>
    <pure-table
      ref="tableRef"
      showOverflowTooltip
      border
      adaptive
      :adaptiveConfig="adaptiveConfig"
      row-key="id"
      alignWhole="center"
      :loading="loading"
      :loading-config="loadingConfig"
      :data="dataList"
      :columns="columns"
    >
      <template #operation="{ row }">
        <el-button type="primary" size="small" @click="editClick(row)"
          >编辑</el-button
        >
        <el-button type="danger" size="small" @click="deleteClick(row)">
          删除
        </el-button>
      </template>
    </pure-table>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="visible"
      v-model="values"
      :form="{ columns: formColumns, rules, labelWidth: 120 }"
      :dialog="{ confirmLoading }"
      :title="edit ? '编辑角色' : '添加角色'"
      @confirm="handleSubmit"
    >
      <template #plus-field-menus>
        <div class="h-200px">
          <el-tree
            ref="treeRef"
            node-key="id"
            :default-checked-keys="defaultCheckedKeys"
            :show-checkbox="true"
            :check-strictly="true"
            default-expand-all
            empty-text="请选择权限"
            :data="treeData"
            :props="treeProps"
            :expand-on-click-node="false"
            check-on-click-node
            @check="treeChecked"
          />
        </div>
      </template>
    </PlusDialogForm>
    <el-dialog v-model="showPreviewImage">
      <img w-full :src="previewImageUrl" :alt="previewImageName" />
    </el-dialog>
  </ElCard>
</template>

<style scoped>
::deep .wot-message-box__icon--warning {
  --el-messagebox-color: red;
  color: red !important;
  fill: red !important;
}
</style>
